package com.ikas.ai.server.module.morningpaper.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageInfo;
import com.ikas.ai.handle.JsonResult;
import com.ikas.ai.model.PageQuery;
import com.ikas.ai.server.module.AbstractBean;
import com.ikas.ai.server.module.morningpaper.model.dto.*;
import com.ikas.ai.server.module.morningpaper.model.po.MorningPaperHisPo;
import com.ikas.ai.server.module.morningpaper.service.MorningPaperFailRecordService;
import com.ikas.ai.server.module.morningpaper.service.MorningPaperHisService;
import com.ikas.ai.server.module.morningpaper.service.MorningPaperOverhaulPlanService;
import com.ikas.ai.server.module.morningpaper.service.MorningPaperVariablesService;
import com.ikas.ai.utils.PageExUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author li.hexian
 * @menu 早报相关接口
 */
@RestController
@RequestMapping("/morningPaper")
public class MorningPaperController extends AbstractBean {
    @Autowired
    MorningPaperVariablesService morningPaperVariablesService;

    @Autowired
    MorningPaperHisService morningPaperHisService;

    @Autowired
    MorningPaperFailRecordService morningPaperFailRecordService;

    @Autowired
    MorningPaperOverhaulPlanService morningPaperOverhaulPlanService;

    /**
     * 获取当日变量集合
     *
     * @return
     */
    @GetMapping("/variables/get")
    public JsonResult getVariables() {
        return JsonResult.ok(morningPaperVariablesService.get());
    }

    /**
     * 修改当日变量集合
     *
     * @param mv
     * @return
     */
    @PostMapping("/variables/update")
    public JsonResult updateVariables(@RequestBody MorningPaperVariablesDto mv) {
        return JsonResult.ok(morningPaperVariablesService.refresh(mv, morningPaperVariablesService.getPosMap()));
    }

    /**
     * 获取当日时间区间文本
     */
    @GetMapping("/getTodayTimeTitle")
    public JsonResult getTodayTimeTitle() {
        MorningPaperTimeTitleDto dto = morningPaperHisService.getTodayTimeTitle();
        return JsonResult.ok(dto);
    }

    /**
     * 获取早报历史列表
     *
     * @return
     */
    @GetMapping("/history/list")
    public JsonResult listHistory(
            @RequestParam(required = false) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai") Date startTime,
            @RequestParam(required = false) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai") Date endTime,
            @RequestParam(required = false) String updater,
            @RequestParam(required = false) String reviewer,
            PageQuery pageQuery
    ) {
        return JsonResult.ok(morningPaperHisService.listHis(startTime, endTime, updater, reviewer, pageQuery));
    }

    /**
     * 根据ID获取早报详情
     *
     * @return
     */
    @GetMapping("/history/getDetailById")
    public JsonResult getHisDetailById(@RequestParam Long id) {
        return JsonResult.ok(morningPaperHisService.getDetail(id));
    }

    /**
     * 当日早报是否已审核
     */
    @GetMapping("/history/hadReviewed")
    public JsonResult hadReviewed() {
        return JsonResult.ok(morningPaperHisService.hadReviewed());
    }

    /**
     * 对当日早报进行审核
     *
     * @return
     */
    @GetMapping("/history/review")
    public JsonResult review() {
        morningPaperHisService.review(getUserName());
        return JsonResult.ok();
    }

    /**
     * 存储历史记录文本
     *
     * @param hisPo
     * @return
     */
    @PostMapping("/history/save")
    public JsonResult saveHistory(@RequestBody MorningPaperHisPo hisPo) {
        morningPaperHisService.refresh(hisPo.getDetail(), getUserName());
        return JsonResult.ok();
    }

    /**
     * 获取执行失败记录
     *
     * @return
     */
    @GetMapping("/failRecord/get")
    public JsonResult getFailRecord() {
        return JsonResult.ok(morningPaperFailRecordService.get());
    }

    /**
     * 修改执行失败记录
     *
     * @param mfv
     * @return
     */
    @PostMapping("/failRecord/update")
    public JsonResult updateFailRecord(@RequestBody MorningPaperFailRecordsDto mfv) {
        morningPaperFailRecordService.refresh(mfv, morningPaperVariablesService.getPosMap());
        return JsonResult.ok();
    }

    /**
     * 获取机组编号集合
     *
     * @return
     */
    @GetMapping("/overhaul/listMachineNos")
    public JsonResult listMachineNos() {
        return JsonResult.ok(morningPaperOverhaulPlanService.listMachineNos());
    }

    /**
     * 获取检修信息文本
     */
    @GetMapping("/overhaul/getDetailText")
    public JsonResult getOverhaulDetailText(String machineNo) {
        return JsonResult.ok(
                morningPaperOverhaulPlanService.getOverhaulDetailText(machineNo)
        );
    }

    /**
     * 获取检修记录
     */
    @GetMapping("/overhaul/list")
    public JsonResult listOverhaul(PageQuery pageQuery) {
        PageExUtil.configPageHelper(pageQuery);
        return JsonResult.ok(
                new PageInfo<>(
                        morningPaperOverhaulPlanService.list()
                )
        );
    }

    /**
     * 添加检修记录
     *
     * @param morningPaperOverhaulDto
     * @return
     */
    @PostMapping("/overhaul/add")
    public JsonResult addOverhaul(@RequestBody MorningPaperOverhaulDto morningPaperOverhaulDto) {
        return JsonResult.ok(morningPaperOverhaulPlanService.savePlan(morningPaperOverhaulDto, getUserName()));
    }

    /**
     * 修改检修记录
     *
     * @param morningPaperOverhaulDto
     * @return
     */
    @PostMapping("/overhaul/update")
    public JsonResult updateOverhaul(@RequestBody MorningPaperOverhaulDto morningPaperOverhaulDto) {
        morningPaperOverhaulPlanService.updatePlan(morningPaperOverhaulDto, getUserName());
        return JsonResult.ok();
    }

    /**
     * 删除检修记录
     *
     * @param id
     * @return
     */
    @GetMapping("/overhaul/delete/{id}")
    public JsonResult delete(@PathVariable Long id) {
        morningPaperOverhaulPlanService.removeById(id);
        return JsonResult.ok();
    }

    /**
     * 早报历史导入模板
     *
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        String sheetName = "历史早报";
        String filename = "历史早报导入模板.xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, sheetName, ExcelType.XSSF), MorningPaperExcelDTO.class, new ArrayList<>());
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(filename, "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        workbook.write(response.getOutputStream());
    }

    @PostMapping("/import")
    public JsonResult importMorningPaperHistoryData(@RequestParam("file") MultipartFile file) throws Exception {
        morningPaperVariablesService.importMorningPaperHistoryData(file, getUser());
        return JsonResult.ok();
    }
}
